/**
 * Created by Liuyk on 2017/9/4.
 */

var VersionInfo = Bmob.Object.extend("VersionInfo");
var query = new Bmob.Query(VersionInfo);
var typeH = "电子班牌后台";
var typeApp = "APP";

// $(function () {

// })
window.onload = function () {
    initBmob();

    var pager = localStorage.getItem("pager");
    document.getElementById("school_name").innerHTML = pager + "学校";
    document.getElementById("date_text").innerHTML = new Date().getTime() + "";
    findAllData();
};

function addTable(tag, results) {
    var index = 0;
    for (var i = 0; i < results.length; i++) {
        var obj = results[i];
        var t = obj.get("tag");
        if (t == tag) {
            index ++;
            var type = obj.get("type");
            if (type == typeH) {
                var table2 =
                    '<td><input class="input_version_h_update" type="text" placeholder="版本号" value=' + obj.get("version") + '> </td> ' +
                    '<td><input class="input_date_h_update" type="text" placeholder="更新时间" value=' + obj.get("date") + '></td> ' +
                    '<td><input class="input_log_h_update" type="text" placeholder="更新日志" value=' + obj.get("log") + '></td> ' +
                    '<td><input class="input_remark_h_update" type="text" placeholder="备注" value=' + obj.get("remark") + '></td> ' +
                    '</tr> </table>';
            }

            if (type == typeApp) {
                var table =
                    '<table id="item_table" align="center" width="width" height="height" border="1" cellspacing="0"> <tr> <th></th> <th>版本</th> <th>时间</th> <th>日志</th> <th>备注</th> </tr> <tr> ' +
                    '<td>APP</td>' +
                    '<td><input class="input_version_app_update" type="text" placeholder="版本号" value=' + obj.get("version") + ' > </td> ' +
                    '<td><input class="input_date_app_update" type="text" placeholder="更新时间" value=' + obj.get("date") + '></td> ' +
                    '<td><input class="input_log_app_update" type="text" placeholder="更新日志" value=' + obj.get("log") + '></td> ' +
                    '<td><input class="input_remark_app_update" type="text" placeholder="备注" value=' + obj.get("remark") + '></td> </tr> ' +
                    '<tr> <td>后台</td>';
            }

            if(index == 2){
                var tagHtml = '<span class="tag_text" id="tag' + t + ' "' + ' style="align-self: center; display: block; height: 50px; line-height: 50px">'
                    + t + '</span>';
                var delHtml = '<span class="del_data_item" id="del' + t + '" ' + ' style="cursor: pointer; font-size: 30px; margin-left: 20px;" >删除</span>';
                var commitHtml = '<span class="commit_data_item" id="commit' + t + '" ' + ' style="cursor: pointer; font-size: 30px" >提交</span>';

                $('#table').append(tagHtml, table + table2, commitHtml, delHtml);
            }
        }
    }

    $(document).ready(function () {
        //页面加载完成
    });
}

function addClick(results) {
    //删除数据
    $(".del_data_item").each(function (index, item) {
        $(this).click(index, function () {
            console.log(item.id.replace("del", ""));
            console.log(index);
            // var dataList = $("表格class"); //在获取一次可以获取到你append后所有的表单
            // var _thisForm = dataList.eq(index);

            var itemTag = item.id.replace("del", "");
            var delItem = [];
            for (var k = 0; k < results.length; k++) {
                var itemObj = results[k];
                if (itemObj.get("tag") == itemTag) {
                    delItem[delItem.length] = itemObj.id;
                }
            }
            delTable(delItem);
        })
    });

    //修改数据
    $(".commit_data_item").each(function(index, item){
        $(this).click(index, function(){
            console.log(item.id.replace("commit", ""));
            console.log(index);

            var appDataParams = [];//所有app数据参数
            var hDataParams = [];//所有后台数据参数

            //获取APP的表单数据
            var appVersionDataList = $(".input_version_app_update"); //在获取一次可以获取到你append后所有的表单
            var appUpdateDataList = $(".input_date_app_update");
            var appLogDataList = $(".input_log_app_update");
            var appRemarkDataList = $(".input_remark_app_update");

            var appVersionDataThis = appVersionDataList.eq(index);
            var appUpdateDataThis = appUpdateDataList.eq(index);
            var appLogDataThis = appLogDataList.eq(index);
            var appRemarkDataThis = appRemarkDataList.eq(index);
            appDataParams[0] = appVersionDataThis[0].value;
            appDataParams[1] = appUpdateDataThis[0].value;
            appDataParams[2] = appLogDataThis[0].value;
            appDataParams[3] = appRemarkDataThis[0].value;
            console.log(appDataParams[0]);
            console.log(appDataParams[1]);
            console.log(appDataParams[2]);
            console.log(appDataParams[3]);

            //获取后台的表单数据
            var hVersionDataList = $(".input_version_h_update"); //在获取一次可以获取到你append后所有的表单
            var hUpdateDataList = $(".input_date_h_update");
            var hLogDataList = $(".input_log_h_update");
            var hRemarkDataList = $(".input_remark_h_update");

            var hVersionDataThis = hVersionDataList.eq(index);
            var hUpdateDataThis = hUpdateDataList.eq(index);
            var hLogDataThis = hLogDataList.eq(index);
            var hRemarkDataThis = hRemarkDataList.eq(index);
            hDataParams[0] = hVersionDataThis[0].value;
            hDataParams[1] = hUpdateDataThis[0].value;
            hDataParams[2] = hLogDataThis[0].value;
            hDataParams[3] = hRemarkDataThis[0].value;

            var itemTag = item.id.replace("commit", "");
            var updateItem = [];
            for (var k = 0; k < results.length; k++) {
                var itemObj = results[k];
                if (itemObj.get("tag") == itemTag) {
                    if (itemObj.get("type") == typeApp) {
                        updateItem[0] = itemObj.id;
                    } else {
                        updateItem[1] = itemObj.id;
                    }
                }
            }
            updateApp(updateItem, appDataParams, hDataParams);
        })
    })
}

function changerTime() {
    $(document).ready(function () {
        $('.date_text').each(function () {
            var time = new Date().getTime() + " ";
            $(this).html(time);
        });
    });
}

function commitData() {
    var time = new Date().getTime();
    commitDataTrailing(time);
}

//提交后台系统更新日志
function commitDataTrailing(time) {
    var version = $('#input_version_h')[0].value;
    var date = $('#input_date_h')[0].value;
    var log = $('#input_log_h')[0].value;
    var remark = $('#input_remark_h')[0].value;

    var VersionInfo = Bmob.Object.extend("VersionInfo");
    var versionInfo = new VersionInfo();
    versionInfo.set("type", typeH);
    versionInfo.set("school", localStorage.getItem("pager"));
    versionInfo.set("tag", time + "");
    versionInfo.set("version", version + "");
    versionInfo.set("date", date + "");
    versionInfo.set("log", log + "");
    versionInfo.set("remark", remark + "");
    versionInfo.save(null,
        {
            success: function (versionInfo) {
                commitDataApp(time);
            },
            error: function (versionInfo, error) {
                // 添加失败
                alert('数据失败，错误信息：' + error.description);
            }
        });
}

//提交APP系统更新日志
function commitDataApp(time) {
    var version = $('#input_version_app')[0].value;
    var date = $('#input_date_app')[0].value;
    var log = $('#input_log_app')[0].value;
    var remark = $('#input_remark_app')[0].value;
    var VersionInfo = Bmob.Object.extend("VersionInfo");

    var versionInfo = new VersionInfo();
    versionInfo.set("type", typeApp);
    versionInfo.set("school", localStorage.getItem("pager"));
    versionInfo.set("tag", time + "");
    versionInfo.set("version", version + "");
    versionInfo.set("date", date + "");
    versionInfo.set("log", log + "");
    versionInfo.set("remark", remark + "");
    versionInfo.save(null,
        {
            success: function (versionInfo) {
                alert('提交成功，数据Id: ' + versionInfo.id);
                window.location.href = "version_manager.html";
            },
            error: function (versionInfo, error) {
                // 添加失败
                alert('提交失败，错误信息：' + error.description);
            }
        });
}

//查询所有数据
function findAllData() {
    query.find({
        success: function (results) {
            assembleDataByTag(results);
            addClick(results);
        },
        error: function (error) {
            alert("查询失败: " + error.code + " " + error.message);
        }
    });
}

//数据是两两一组的，依据tag（时间戳）分类合并
function assembleDataByTag(results) {
    //根据学校查询分类数据
    var refactorDataBySchool = [];
    for (var r = 0; r < results.length; r++) {
        var obj = results[r];
        if (obj.get("school") == localStorage.getItem("pager")) {
            refactorDataBySchool[refactorDataBySchool.length] = obj;
        }
    }

    var tags = [];
    for (var i = 0; i < refactorDataBySchool.length; i++) {
        var object = refactorDataBySchool[i];
        var contain = $.inArray(object.get('tag'), tags);//返回大于0, 不包含返回-1
        if (contain == -1) {
            tags[tags.length] = object.get('tag');
        }
    }

    for (var k = 0; k < tags.length; k++) {
        addTable(tags[k], refactorDataBySchool);
    }
}

//删除数据
function delTable(tag) {
    delAppItem(tag);
}

//删除APP数据
function delAppItem(tag) {
    var VersionInfo = Bmob.Object.extend("VersionInfo");
    var query = new Bmob.Query(VersionInfo);
    query.get(tag[0], {
        success: function (object) {
            object.destroy({
                success: function (deleteObject) {
                    delHItem(tag);
                },
                error: function (VersionInfo, error) {

                }
            });
        },
        error: function (object, error) {

        }
    });
}

//删除后台数据
function delHItem(tag) {
    var VersionInfo = Bmob.Object.extend("VersionInfo");
    var query = new Bmob.Query(VersionInfo);
    query.get(tag[1], {
        success: function (object) {
            object.destroy({
                success: function (deleteObject) {
                    alert("删除成功");
                    // $('#item_table').remove();
                    // $('#tag_text').remove();
                    // $('.commit_data_item').remove();
                    // $('.del_data_item').remove();
                    window.location.href = "version_manager.html";
                },
                error: function (VersionInfo, error) {

                }
            });
        },
        error: function (object, error) {

        }
    });
}

//修改APP数据
function updateApp(tag, appDataParams, hDataParams) {
    var VersionInfo = Bmob.Object.extend("VersionInfo");
    query.get(tag[0], {
        success: function (object) {
            object.set("version", appDataParams[0] + "");
            object.set("date", appDataParams[1] + "");
            object.set("log", appDataParams[2] + "");
            object.set("remark", appDataParams[3] + "");
            object.save(null, {
                success: function (objectUpdate) {
                    updateH(tag, hDataParams);
                },
                error: function (model, error) {
                    alert("create object fail");
                }
            });
        },
        error: function (object, error) {
            alert("query object fail");
        }
    });
}

//修改后台数据
function updateH(tag, hDataParams) {
    query.get(tag[1], {
        success: function (object) {
            object.set("version", hDataParams[0] + "");
            object.set("date", hDataParams[1] + "");
            object.set("log", hDataParams[2] + "");
            object.set("remark", hDataParams[3] + "");
            object.save(null, {
                success: function (objectUpdate) {
                    alert("修改成功");
                },
                error: function (model, error) {
                    alert("create object fail");
                }
            });
        },
        error: function (object, error) {
            alert("query object fail");
        }
    });
}

//初始化bmob
function initBmob() {
    Bmob.initialize("692e2955a7784a591f6e417a084f85b6", "7337b6c53a8da0c06e7bd9c00492e997");
}